define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Exchange_interaction, GoPage, $ionicSlideBoxDelegate, $ionicPopup, $window, $timeout, $rootScope, GoPicture, GoDialog, ChatInfo, Auth) {
		$scope.input = new Object();
		$scope.input.articleBuyerKey = "";
		$scope.input.articleSellerKey = "";
		$scope.input.image = new Array();
        $scope.seller_base = new Array();
        $scope.buy_base = new Array();
		//导航切换
		$scope.selectTab = 0;
		$scope.isLoad = false;
		$scope.count_f = null;
		$scope.count_s = null;
		$scope.$on('$ionicView.afterEnter', function() {
			//var lan = 0; //这是状态栏，只有ios的APP才有
			//var tab = 0;
			//var bars = document.getElementById("nav-bar-title");
			//var bar = ((bars != undefined) ? 44 : 0);
			//if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS()) {
			//	lan = 20;
			//}
			var topH = 44;
			//整体高度
			var all = $window.innerHeight;
			var barheader = document.getElementsByClassName("bar-header");//头部标题栏
			if(barheader.length>0){
				angular.forEach(barheader, function(obj) {
					if(obj.offsetHeight>0){
						topH = obj.offsetHeight;
					}
				});
			}

			var exc_top1 = document.getElementById("exc-top1").clientHeight;
			var exc_top2 = document.getElementById("exc-top2").clientHeight;
			$scope.exc_myObj1 = { //滚动条可视范围
				"height": all - topH - exc_top1 - exc_top2 + "px"
			};
			$scope.init_data();
		}, false);
		$scope.activeTab = function(index) {
			$scope.selectTab = index;
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').slide(index);
		};
		$scope.slideChanged = function(index) {
			$scope.selectTab = index;
			$scope.doRefresh();
		};
		
		//禁止左右滑动来切换页面1
		$scope.onTouch = function() {
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').enableSlide(false);
		};
		//禁止左右滑动来切换页面2
		$scope.onRelease = function() {
			$ionicSlideBoxDelegate.$getByHandle('tab-handle').enableSlide(true);
		};
		
		
		//动态响应
		$scope.doShowFile = function() {
			document.getElementById("upfile").click();
		};
		//图片上传
		$scope.onupload = function(val) {
			var fileList = val.files;
			for(var i = 0; i < val.files.length; i++) {
				var reader = new FileReader();
				reader.readAsDataURL(fileList[i]);
				var file = fileList[i];
				reader.onload = function(e) {
					//图片进行压缩处理
					GoPicture.compress(file,e.target.result, 50, function(base64) {
						$scope.$apply(function() {
							$scope.input.image[0] = {
								"image": base64
							}
							val.value = "";
						});
					});
				}
			}
		};
		var myPopup; //申请讨论组
		$scope.showPopup = function(val) { //绑定数据时要注意，如果是数组，则通过$index传入下标；如果是json，则传入key
			$scope.input.name = '';
			$scope.input.image = new Array();
			$scope.input.group_brief = '';
			myPopup = $ionicPopup.show({ //show()
				templateUrl: 'templates/modal/apply_group.html',
				title: "申请讨论组",
				scope: $scope, //绑定数据，必须写这行
				buttons: [{
					text: "确定",
					type: "button-assertive",
					onTap: function() { // 当点击保存按钮时，执行该函数
						if($scope.input.name == ""){
							GoDialog.toast("请输入讨论组名称！");
							e.preventDefault();
							return;
						}
						if($scope.input.image.length ==0){
							GoDialog.toast("请上传讨论组图片！");
							e.preventDefault();
							return;
						}
						Exchange_interaction.apply_discussion($scope.input.name, $scope.input.image[0].image, $scope.input.group_brief, function(data) {

							if(data.success == true) {
								GoDialog.toast("申请讨论组成功，请等待审核！");
							} else {
								GoDialog.toast(data.msg);

							}
						})
					}
				}]
			});
		};

		var myPopup_article; //文章
		$scope.showPopup_article = function(val) { //绑定数据时要注意，如果是数组，则通过$index传入下标；如果是json，则传入key
			$scope.showinfo = val.data;
			myPopup_article = $ionicPopup.show({ //show()
				templateUrl: 'templates/modal/article_detail.html',
				title: val.title,
				scope: $scope, //绑定数据，必须写这行
				buttons: [{
					text: "确定",
					type: "button-assertive",
					onTap: function() { // 当点击保存按钮时，执行该函数
					}
				}]
			});
		}

		//点击其他区域关闭弹出窗
		var htmlEl = angular.element(document.querySelector('html'));
		htmlEl.on('click', function(event) {
			if(event.target.nodeName === 'HTML') {
				if(myPopup) {
					myPopup.close();
				}
				if(myPopup_article) {
					myPopup_article.close();
				}
			}
		});


		//进入群聊
		$scope.onMovetoChat = function(index, group_id, is_group_member, gnum, max_gnum) {
			if(index == 1) {
				if(is_group_member == true) {

					GoPage.go_states("exchange_interaction_chat", { "group_id": group_id });
				} else {
					GoDialog.toast("您不是群组成员");
				}
			} else {
				//				if(parseInt(gnum)<parseInt(max_gnum) ){
				//					GoPage.go_states("exchange_interaction_chat",{"group_id":group_id});
				//				}else{
				//					GoDialog.toast("讨论组人数已满");
				//				}

				Exchange_interaction.join_group(group_id, function(data) {
					if(data.rtnCode == 0 || data.rtnCode == 5) {
						GoPage.go_states("exchange_interaction_chat", { "group_id": group_id });
					} else {
						GoDialog.toast(data.rtnMsg);
					}
				})
			}
		};

		$scope.init_data = function() {
			$scope.input.group_key = '';
			$scope.input.discussion_key = '';
			$scope.get_list(1, $scope.input.group_key, true);
			$scope.get_list(2, $scope.input.discussion_key, true);
			$scope.get_loginfo();
			$scope.get_base();
		}

		$scope.get_base = function() {
			//卖家入门
			Exchange_interaction.get_base(1, 1, $scope.input.articleSellerKey, function(data) {
				$scope.seller_base = data.article;
			});
			//买家入门
			Exchange_interaction.get_base(1, 2, $scope.input.articleBuyerKey, function(data) {
				$scope.buy_base = data.article;
			});
		};

		//小小图登录信息
		$scope.get_loginfo = function() {
			//判断本地是否保存有小小图登录信息
			var is_chatLogin = ChatInfo.get_isInfos();
			if(is_chatLogin == false && Auth.check_loginInfo())
				Exchange_interaction.get_loginfo(function(data) {
					$scope.chat_url = data.chat_url;
					$scope.login_code = data.login_code;
					$scope.soket_url = data.soket_url;
					//初次保存小小图登录信息
					ChatInfo.save_chat_loginInfo($scope.chat_url, $scope.login_code, $scope.soket_url);
				})
		};
		$scope.get_list = function(type, key, is_first) {
			Exchange_interaction.get_list(type, 1, key, function(data) {
				if(type == 1) {
					$scope.group = data;
					$scope.input.group_nPage = 1;
				} else {
					$scope.discussion = data;
					$scope.input.discussion_nPage = 1;
				}

			}, function() {
				if(is_first == false) {
					$scope.$broadcast('scroll.refreshComplete');
				}

				$timeout(function() {
					$scope.isLoad = false; //可以加载
				}, 1000);

			})
		};
		$scope.doSearch = function(key) {
			if($scope.selectTab == 0) {
				$scope.input.group_key = key;
				$scope.get_list(1, $scope.input.group_key, false);
			}
			else if($scope.selectTab == 1) {
				$scope.input.discussion_key = key;
				$scope.get_list(2, $scope.input.discussion_key, false);
			}
			else if($scope.selectTab == 2) {

			}
			else {

			}
		};

		$scope.doRefresh = function() {
			$scope.isLoad = true;
			if($scope.selectTab == 0) {
				$scope.get_list(1, $scope.input.group_key, false);
			}
			else if($scope.selectTab == 1) {
				$scope.get_list(2, $scope.input.discussion_key, false);
			}

			else if($scope.selectTab == 2) {
				$scope.buyPage = 1;
				Exchange_interaction.get_base(1, 2, function(data) {
					if(data != null) {
						$scope.buy_base = data.article;
					} else {
						$scope.buy_base = new Array();
					}
				}, function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
			else {
				$scope.sellerPage = 1;
				Exchange_interaction.get_base(1, 1, function(data) {
					if(data != null) {
						$scope.seller_base = data.article;
					} else {
						$scope.seller_base = new Array();
					}
				}, function() {
					$scope.$broadcast('scroll.refreshComplete');
				});
			}
		};
		$scope.doRefreshMore = function() {
			$scope.isLoad = true;
			if($scope.selectTab == 0) {
				if($scope.group.group == undefined) {
					$scope.input.group_nPage = 0;
				} else {
					if($scope.group.page.count <= $scope.group.group.length) {
						$scope.$broadcast('scroll.infiniteScrollComplete');
						if($scope.group.page.count < $scope.input.group_nPage * 6) {
							$scope.input.group_nPage -= 1;
							$scope.count_f = $scope.input.group_nPage * 6;
						} else {
							$scope.count_f = null;
						}
					}
				}
				Exchange_interaction.get_list(1, $scope.input.group_nPage + 1, $scope.input.group_key, function(data) {
					if(data.group.length != 0) {
						if($scope.group.group != undefined) {
							if($scope.count_f != null)
								$scope.group.group.splice($scope.count_f, $scope.group.page.count - $scope.count_f);
							$scope.group.group = $scope.group.group.concat(data.group);
							$scope.input.group_nPage += 1;
						} else {
							$scope.group.group = data.group;
							$scope.input.group_nPage += 1;
						}
					}
				}, function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false; //可以加载
					}, 1000);
				})
			}
			else if($scope.selectTab == 1) {
				if($scope.discussion.group == undefined) {
					$scope.input.discussion_nPage = 0;
				} else {
					if($scope.discussion.page.count <= $scope.discussion.group.length) {
						$scope.$broadcast('scroll.infiniteScrollComplete');
						if($scope.discussion.page.count < $scope.input.discussion_nPage * 6) {
							$scope.input.discussion_nPage -= 1;
							$scope.count_s = $scope.input.discussion_nPage * 6;
						} else {
							$scope.count_s = null;
						}
					}
				}
				Exchange_interaction.get_list(2, $scope.input.discussion_nPage + 1, $scope.input.discussion_key, function(data) {
					if(data.group.length != 0) {
						if($scope.discussion.group != undefined) {
							if($scope.count_s != null)
								$scope.discussion.group.splice($scope.count_s, $scope.discussion.page.count - $scope.count_s);
							$scope.discussion.group = $scope.discussion.group.concat(data.group);
							$scope.input.discussion_nPage += 1;
						} else {
							$scope.discussion.group = data.group;
							$scope.input.discussion_nPage += 1;
						}
					}
				}, function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false; //可以加载
					}, 1000);
				})
			}
			else if($scope.selectTab == 2) {
				Exchange_interaction.get_base($scope.buyPage + 1, 2, function(data) {
					if(data != null && data.article.length > 0) {
						$scope.buy_base = $scope.buy_base.concat(data.article);
						$scope.buyPage += 1;
					}
				}, function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				});
			}
			else {
				Exchange_interaction.get_base($scope.sellerPage + 1, 1, function(data) {
					if(data != null && data.article.length > 0) {
						$scope.seller_base = $scope.seller_base.concat(data.article);
						$scope.sellerPage += 1;
					}
				}, function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				});
			}
		};

		


		//获取用户信息
		Exchange_interaction.getUserInfo(function(data){
			$scope.userInfo = data;
		})

		//跳转到第三方链接。confirm: function(title, message, callOK, callCancel)
		$scope.onshow_outLink = function(){
			var info = Auth.get_loginInfo();
            		//$scope.outUrl = HTTP_URL_BBS;
			if(!info){
				GoDialog.confirm("请求失败","请先登录",function(){
					GoPage.go_states("t-login");
				})
			}else if(info.verify_email!="Y"){//大写
				GoDialog.confirm("请求失败","请先绑定邮箱",function(){
					GoPage.go_states("linkemail");
				})
			}else{
				GoPage.go_states('bbs');
				//$scope.outUrl = $scope.outUrl+"?session="+$scope.userInfo.session;
				//GoPage.go_link($scope.outUrl);
			}
		}


	}

	controller.$inject = ['$scope', 'Exchange_interaction', 'GoPage', '$ionicSlideBoxDelegate', '$ionicPopup', '$window', '$timeout', '$rootScope', 'GoPicture', 'GoDialog', 'ChatInfo', 'Auth'];

	return app.registerController("exchange_interactionctrl",controller);
});